﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace CommonProject.Common
{
    public static class StreamExtensions
    {
        /// <summary>
        /// 复制内存到内存
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static Stream CopyToMemoryStream(this Stream source)
        {
            Stream destination = new MemoryStream((int)source.Length);
            source.Position = 0;
            source.CopyTo(destination);
            destination.Position = 0;
            return destination;
        }
        //Stream destination = source.CopyToMemoryStream();

        /// <summary>
        /// 保存到文件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="outputPath"></param>
        public static void CopyToFileStream(this Stream source, string outputPath)
        {
            // 确保MemoryStream的位置回到开始
            source.Position = 0;

            string path = Path.GetDirectoryName(outputPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // 创建一个FileStream用于写入数据
            using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
            {
                // 将MemoryStream的内容复制到FileStream
                source.CopyTo(fileStream);
            }
        }
    }
}